/**
 * Created by Mark on 2018/4/11.
 * 用户模块:更新密码
 */

require("./user-password-update.css");
require("page/common/nav/nav.js");
require("page/common/header/header.js");
var navSide = require("page/common/nav-side/nav-side.js");
var _user = require("service/user-service.js");
var _mm = require("util/mm.js");

var page = {
    init : function(){
        this.onLoad();
        this.bindEvent();
    },
    //初始化加载的信息
    onLoad : function(){
        navSide.init({//加载侧边导航
            name : "user-pass-update",
        });

    },
    bindEvent : function(){
        var _this = this;
        $(document).on("click","#submit-password",function(){
            var userInfo = {
                password : $.trim($("#password").val()),
                passwordNew : $.trim($("#password-new").val()),
                passwordConfirm : $.trim($("#password-confirm").val()),

            };
            var validateResult = _this.validateFrom(userInfo);
            if(validateResult.status){//验证通过
                _user.updatePassword({
                        passwordOld : userInfo.password,
                        passwordNew : userInfo.passwordNew
                    },
                    function(res){
                        _mm.successTips(res.msg);
                        _user.logout(
                            function(res){
                               _mm.doLogin();
                            },
                            function(errMsg){
                                _mm.errorTips(errMsg);
                            }
                        );
                    },
                    function(err){
                        _mm.errorTips(err.msg);
                    });
            }else{
                _mm.errorTips(validateResult.msg);
            }
        });

    },
    validateFrom : function(formData){//验证密码
        var result = {
            status : false,
            msg : ""
        };
        //验证原始密码是否为空
        if(!_mm.validate(formData.password,"require")){
            result.msg = "输入原始密码不能为空！";
            return result;
        }
        //新密码不能为空且长度不得少于6位
        if(!formData.passwordNew ||formData.passwordNew.length < 6){
            result.msg = "新密码不得少于6位数";
            return result;
        }
        //验证两次输入的新密码是否一致
        if(formData.passwordNew !== formData.passwordConfirm){
            result.msg = "两次输入的新密码不一致！";
            return result;
        }
        //通过验证返回，正确提示
        result.status = true;
        result.msg = "验证通过";
        return result;
    },


};
$(function(){
    page.init();
});


